package org.example.controller;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestClient;

import java.util.List;
import java.util.Random;

@RestController
public class UserController2 {
    private final DiscoveryClient discoveryClient;
    private final RestClient restClient;

    public UserController2(DiscoveryClient discoveryClient, RestClient.Builder restClientBuilder) {
        this.discoveryClient = discoveryClient;
        restClient = restClientBuilder.build();
    }

    @RequestMapping("/user2/order/query/{id}")
    public String queryOrder(@PathVariable  int id){
        List<ServiceInstance> instances = discoveryClient.getInstances("micro-eureka-order");
        ServiceInstance instance = instances.get(new Random().nextInt(instances.size()));
        String responses = restClient.get()
                .uri(instance.getUri() + "/order/"+id)
                .retrieve()
                .body(String.class);
        return "[server:"+instance.getServiceId()+",port:"+instance.getPort() + "]"+responses;
    }

}
